<template>
  <zeda-dialog
    v-model="visible"
    title="分配数据权限"
    width="500px"
    :before-close="handleClose"
    class="dialog-content"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="apsForm"
    ></aps-form>
    <el-form style="margin-left: 5px;" v-show="dataScopeChose == '2'" :model="form" label-width="80px">
      <el-form-item label="数据权限">
        <el-checkbox
          v-model="deptExpand"
          @change="handleCheckedTreeExpand($event, 'dept')"
          >展开/折叠</el-checkbox
        >
        <el-checkbox
          v-model="deptNodeAll"
          @change="handleCheckedTreeNodeAll($event, 'dept')"
          >全选/全不选</el-checkbox
        >
        <el-checkbox
          v-model="form.deptCheckStrictly"
          @change="handleCheckedTreeConnect($event, 'dept')"
          >父子联动</el-checkbox
        >
        <el-tree
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="dept"
          node-key="id"
          :check-strictly="!form.deptCheckStrictly"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      </el-form-item>
    </el-form>
    <form-button
      slot="footer"
      :loading="loading"
      :submitText="'确定'"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>

<script>
import FormButton from "@/components/FormButton";
import { getRole, dataScope } from "@/api/system/role";
import {
  treeselect as deptTreeselect,
  roleDeptTreeselect,
} from "@/api/system/dept";
export default {
  dicts: [],
  components: {
    FormButton,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false, // 按钮加载中判断
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限",
        },
        {
          value: "2",
          label: "自定数据权限",
        },
        {
          value: "3",
          label: "本部门数据权限",
        },
        {
          value: "4",
          label: "本部门及以下数据权限",
        },
        {
          value: "5",
          label: "仅本人数据权限",
        },
      ],
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      deptExpand: true,
      deptNodeAll: false,
      dataScopeChose: null,
      deptOptions: [],
      apsForm: {
        formRef: "apsForm",
        formData: {},
        labelWidth: "auto",
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              dataScope: [
                {
                  required: true,
                  message: "请选择权限范围",
                  trigger: ["blur", "change"],
                },
              ],
            },
          },
          properties: {
            roleName: {
              typeName: "el-input",
              label: "角色名称",
              disabled: true,
            },
            dataScope: {
              label: "权限范围",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = [...that.dataScopeOptions];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.apsForm?.getFieldsValue().dataScope;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择权限范围",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.apsForm?.setFieldValue(
                            "dataScope",
                            value
                          );
                          that.dataScopeChose = value;
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (String(this.id).length > 0) {
          this.getInfo();
        }
      }
    },
  },
  methods: {
    getInfo() {
      getRole(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          console.log(newData);
          newData.areaId = res?.data?.douDistrictId;
          this.dataScopeChose = newData?.dataScope ?? "1";
          this.$refs?.apsForm?.setFieldsValue(newData);
          this.handleDataScope();
        })
        .catch(() => {
          // // this.$message.error("系统错误,请联系管理员!");
        });
    },
    submit() {
      const data = {
        ...this.$refs.apsForm.getFieldsValue(),
      };
      if (data.dataScope == "2") {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        data.deptIds = this.form.deptIds;
        data.deptCheckStrictly = this.form.deptCheckStrictly;
      }
      console.log(data, "qqcs");
      this.$refs.apsForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.scopeRequest(data);
        } else {
          return false;
        }
      });
    },
    scopeRequest(data) {
      dataScope(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handleClose(status) {
      this.$refs["apsForm"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
    /** 分配数据权限操作 */
    handleDataScope() {
      this.reset();
      const roleDeptTreeselect = this.getRoleDeptTreeselect(this.id);
      getRole(this.id).then((response) => {
        this.form = response.data;
        this.$nextTick(() => {
          roleDeptTreeselect.then((res) => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
      });
    },
    reset() {
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: "0",
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined,
      };
      this.deptNodeAll = false;
      this.deptExpand = true;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询部门树结构 */
    getRoleDeptTreeselect(roleId) {
      return roleDeptTreeselect(roleId).then((response) => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "dept") {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/assets/styles/mixin.scss";
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
.dialog-content {
  margin-top: 100px;
  ::v-deep .el-tree {
    max-height: 300px;
    overflow-y: scroll;
    @include scrollBar3(rgba(138, 133, 133, 0.5));
  }
}
</style>
